package com.ptu.servlet;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.ptu.entity.Employee;
import com.ptu.entity.ExpImage;
import com.ptu.entity.Expense;
import com.ptu.entity.ExpenseItem;
import com.ptu.service.ExpImageService;
import com.ptu.service.ExpenseItemService;
import com.ptu.service.ExpenseService;
import com.ptu.service.impl.ExpImageServiceImpl;
import com.ptu.service.impl.ExpenseItemServiceImpl;
import com.ptu.service.impl.ExpenseServiceImpl;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 *
 */
@WebServlet("/ptu/ExpenseServlet")
public class ExpenseServlet extends BaseServlet {

    private ExpenseService expService = new ExpenseServiceImpl();

    private ExpenseItemService eiService = new ExpenseItemServiceImpl();

    private ExpImageService imageService = new ExpImageServiceImpl();

    private int id = 0;

    // 查询待审核记录
    protected void  expFindMore(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Employee emp = (Employee) req.getSession().getAttribute("emp");

        String empId = emp.getEmpId();

        List<Expense> list = expService.findExpenseMore(empId);

        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();

        String json = gson.toJson(list);

        resp.getWriter().print(json);

    }

    // 查询我的报销
    protected void  showMyExpense(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Employee emp = (Employee) req.getSession().getAttribute("emp");
        List<Expense> myExpense = expService.findMyExpense(emp.getEmpId());
        req.setAttribute("myExpense", myExpense);
        req.getRequestDispatcher("/myExpense.jsp").forward(req, resp);
    }

    // 删除报销单
    protected void  delExpense(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int expid = Integer.parseInt(req.getParameter("expId"));

        expService.removeExp(expid);

        showMyExpense(req, resp);
    }

    // 添加报销单操作
    protected void  expAdd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        fileUpLoad(req, resp);

    }

    protected void fileUpLoad(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Employee emp = (Employee) req.getSession().getAttribute("emp");

        java.sql.Date expTime = new java.sql.Date(new java.util.Date().getTime());

        id = idGenerator();

        String expDesc = "";

        String nextAuditor = "";

        String[] types = new String[5];

        String[] amounts = new String[5];

        String[] itemDescs = new String[5];

        ExpImage image = null;

        //【A】创建文件上传的工厂对象
        FileItemFactory factory = new DiskFileItemFactory();

        //【B】获得文件上传的组件对象
        ServletFileUpload upload = new ServletFileUpload(factory);

        // 设置文件上传的编码
        upload.setHeaderEncoding("utf-8");

        try {
            //【C】获得前台所有的表单数据
            List<FileItem> list = upload.parseRequest(req);

            System.out.println(list);

            String  filename = "";

            String filetype = "";

            int i = 0;

            for(FileItem item : list) {

                // System.out.println(item.getFieldName()+"--"+item.getSize()+"--"+item.getName()+"--"+item.getContentType()+"--"+item.isFormField());

                if(!item.isFormField()){
                    //证明是文件表单
                    filetype = item.getContentType();
                    String subString = item.getName().substring(item.getName().lastIndexOf("."));

                    /******【F】设置上传文件的类型  .jpg  .png  .gif */
                    if(!(".jpg".equals(subString)||".png".equals(subString)||".gif".equals(subString))){
                        req.setAttribute("msg","上传文件的类型必须是图片");
                        req.getRequestDispatcher("/expenseAdd.jsp").forward(req,resp);
                        return;
                    }

                    /*****【E】指定上传文件的大小*******/
                    if(item.getSize()>1*1024*1024){
                        req.setAttribute("msg","文件最大为20k");
                        req.getRequestDispatcher("/expenseAdd.jsp").forward(req,resp);
                        return;
                    }

                    /****【D】使用UUID保证文件不重复**********/
                    String uuid = UUID.randomUUID().toString();

                    // 1.jpg   1.1.jpg   .jpg
                    filename = uuid + subString;

                    //文件的上传
                    /***【C】动态获得服务器目录*/
                    String realPath = req.getServletContext().getRealPath("/imgs");
//                    String realPath = "D:\\OA System\\ptuoa\\web\\imgs";

                    /****【B】创建文件夹*****/
                    File file = new File(realPath);
                    if(!file.exists()){
                        file.mkdirs();
                    }
                    item.write(new File(file,filename));

                    image = new ExpImage();
                    image.setExpid(id);
                    image.setRealname(item.getName());
                    image.setFilename(filename);
                    image.setFiletype(subString);

                } else {
                    //文本表单项
                    if("type".equals(item.getFieldName())){
                        types[i] = item.getString("utf-8");
                    }
                    if("amount".equals(item.getFieldName())){
                        amounts[i] = item.getString();
                    }
                    if("itemDesc".equals(item.getFieldName())){
                        itemDescs[i] = item.getString("utf-8");
                        i++;
                    }
                    if("nextAuditor".equals(item.getFieldName())){
                        nextAuditor = item.getString("utf-8");
                    }
                    if("expDesc".equals(item.getFieldName())){
                        expDesc = item.getString("utf-8");
                    }
                }
            }

            List<ExpenseItem> items = new ArrayList<>();

            double count = 0;

            for(int index=0; index<types.length; index++){
                if(types[index] != null) {
                    String type = types[index];

                    Double amount = Double.parseDouble(amounts[index]);

                    String itemDesc = itemDescs[index];

                    ExpenseItem expenseItem = new ExpenseItem(type,amount,itemDesc);

                    items.add(expenseItem);

                    count += amount;
                }
            }

            Expense exp = new Expense(id, emp.getEmpId(), count, expTime, expDesc, nextAuditor,null, "0");

            // 2. 数据处理
            int add = expService.add(exp, items);
            int i1 = imageService.addImage(image);

            // 3. 给用户做出响应
            if(add > 0 || i1 > 0) {
                showMyExpense(req, resp);
            } else {
                req.setAttribute("msg", "报销单添加失败");
                req.getRequestDispatcher("/expenseAdd.jsp").forward(req, resp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    // 创建 Expense 对象
    private Expense creatExpense(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String empid = req.getParameter("empid");
        String totalamount = req.getParameter("totalamount");
        Date exptime = toDate(req.getParameter("exptime"));
        String expdesc = req.getParameter("expdesc");
        String nextauditor = req.getParameter("nextauditor");
        String lastResult = req.getParameter("lastResult");
        String status = req.getParameter("status");
        if(status == null) { status = "1"; }

        Expense expense = new Expense();
        expense.setExpId(idGenerator());
        expense.setEmpId(empid);
        expense.setExpTime(exptime);
        expense.setExpDesc(expdesc);
        expense.setNextAuditor(nextauditor);
        expense.setStatus(status);
        return expense;
    }

    // 随机生成报销单id
    private int idGenerator() {
        return (int) (System.currentTimeMillis()%1000000);
    }

    private Date toDate(String value) {
        try {
            return Date.valueOf(value);
        }catch (IllegalArgumentException i) {
            return null;
        }
    }
}
